package utils;

import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class Utils {
    
    public static String PDF_FOLDER = "letters";
    public static String DOCTOR_FOLDER = "doctor";
    public static String PATIENT_FOLDER = "patient";
    public static String IMAGE_FOLDER = "images";
    public static String STYLE_FOLDER = "styles";
    
    public static void printHeader(HttpServletRequest request, PrintWriter out, String titolo) {
        out.println("<!DOCTYPE html>\n" +
                    "<html>\n" +
                    "   <head>\n" +
                    "       <meta charset=\"utf-8\">\n" +
                    "       <title>"+titolo+"</title>\n" +
                    "<link href=\"" + Utils.getPath(request.getContextPath(), Utils.STYLE_FOLDER, "style.css") + "\" rel=\"stylesheet\" type=\"text/css\" />\n"+
                    "       <style type=\"text/css\">\n" +    
                    "           body {\n" +
                    "               padding-top: 30px;\n" +
                    "               padding-bottom: 30px;\n" +
                    "               background: #ffffff;\n" +
                    "           }\n" +
                    "       </style>\n" +
                    "   </head>\n" +
                    "   <body>\n");
    }
    
    public static void printFooter(PrintWriter out) {
        out.println("           </div>\n" +
                    "       </div>\n" +
                    "   </body>\n"+
                    "</html>\n");
    }
    
    
    
    public static void printError(HttpServletRequest request, PrintWriter out, String messageError) {
        out.println("       <div class=\"container-fluid-medium\">\n" +
                    "           <div class=\"row-fluid\">\n" +
                    "               <h1>Error</h1>\n" +
                    "               <br>\n" +
                    "               <div class=\"alert alert-error\">\n" +
                    "                   "+messageError+"\n" +
                    "               </div>\n");
    }
    
    
    
    public static void printSuccess(HttpServletRequest request, PrintWriter out, String messageSuccess) {
        out.println("       <div class=\"container-fluid-medium\">\n" +
                    "           <div class=\"row-fluid\">\n" +
                    "               <h1>Success</h1>\n" +
                    "               <br>\n" +
                    "               <div class=\"alert alert-success\">\n" +
                    "                   "+messageSuccess+"\n" +
                    "               </div>\n");
    }
    
    
    
    /**
     * Stampa l'header della pagina con le informazioni dell'utente (Welcome message, cookies)
     * @param request
     * @param out 
     */
    public static void printUserInfo(HttpServletRequest request, PrintWriter out) {
        User loggedUser = (User)request.getSession().getAttribute("user");
        
        Cookie[] cookies = request.getCookies();
        
        //i filtri dovrebbero controllare l'esistenza dell'utente nella sessione
        
        out.println("       <div class=\"container-fluid-medium\">\n" +
                    "           <div class=\"row-fluid\">\n" +
                    "                <div class=\"span6\">\n" +
                    "                    <div class=\"well\">\n" +
                    "                        <ul class=\"nav nav-list\">\n");
        
        if(loggedUser.getUserType() == User.UserType.DOCTOR) {
        out.println("                          <li class=\"nav-header\">Vaccini</li>\n" +
                    "                          <li><a href=\"dottore_proceduraRichiamoPazienti.html\">Procedura Richiamo Pazienti</a></li>\n" +
                    "                          <li><a href=\"dottore_visualizzaRichiamati.html\">Visualizza Pazienti Richiamati</a></li>\n" +
                    "                          <li class=\"nav-header\">Utente</li>\n\n" +
                    "                          <li class=\"active\"><a href=\"#\">Home</a></li>");   
        } else {
        out.println("                          <li class=\"nav-header\">Vaccini</li>\n" +
                    "                          <li><a href=\"patient/Paziente_VisualizzaRichiami\">Visualizza Ultimi Vaccini</a></li>\n" +
                    "                          <li class=\"nav-header\">Utente</li>\n\n" +
                    "                          <li class=\"active\"><a href=\"#\">Home</a></li>");  
        }        

        out.println("                          <li><a href=\"Logout\">Logout</a></li>\n" +
                    "                        </ul>\n" +
                    "                    </div>\n" +
                    "                </div>" +                
                    "                <div class=\"well span6\" style=\"padding:10px; text-align: center;\">\n" +
                    "                         <img src=\"images/"+loggedUser.getPhoto()+"\">\n" +
                    "                         <div class=\"caption\">\n" +
                    "                             <h3>"+loggedUser.getName()+" "+loggedUser.getSurname()+"</h3>\n" +
                    "                             <p>  \n" +
                    "                                 <small>username</small> \n" +
                    "                                 <code>"+loggedUser.getUsername()+"</code>\n" +
                    "                                 <br>\n" +
                    "                                 <small>data ultimo login</small> \n" +
                    "                                 <br>\n" +
                    "                                 <small>\n");
        
        for(int i=0;i<cookies.length;i++)
            if(cookies[i].getName().equals("Vaccination-lastlogin-"+loggedUser.getUsername()))
                out.println("" + cookies[i].getValue() +"\n"
                        + "     <br>\n"
                        + "     </small>\n"
                        + "     <br>\n"
                        + "     <small>\n");
        
        out.println("           </small>\n" +
                    "       </div>\n");
    }
    
    
    /**
     * Verifica se la stringa inserita è un numero intero
     * @param value
     * @return 
     */
    public static boolean tryParseInt(String value) {
        try {
            Integer.parseInt(value);
            return true;
        }
        catch(Exception e){
            return false;
        }
    }
    
    /**
     * Verifica se la stringa inserita è un numero intero positivo
     * @param value
     * @return 
     */
    public static boolean tryParseUInt(String value) {
        try {
            if(Integer.parseInt(value)>=0)
                return true;
            else
                return false;
        }
        catch(Exception e){
            return false;
        }
    }
    
    // funzioni per la formattazione della data
    public static String formatDate(Date date) {
        SimpleDateFormat formattedDate = new SimpleDateFormat("dd / MM / yyyy");
        return formattedDate.format(date);
    }
    public static String formatDate(Timestamp date) {
        SimpleDateFormat formattedDate = new SimpleDateFormat("dd / MM / yyyy");
        return formattedDate.format(date);
    }
    
    // funzioni per la formattazione di data e ora
    public static String formatDateTime(Date datetime) {
        SimpleDateFormat formattedTime = new SimpleDateFormat("dd / MM / yyyy - HH:mm:ss");
        return formattedTime.format(datetime);
    }
    
    // funzioni per la formattazione di data e ora
    public static String formatDateTimeSQL(Date datetime) {
        SimpleDateFormat formattedTime = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        return formattedTime.format(datetime);
    }
    
    public static String formatDateTime(Timestamp datetime) {
        SimpleDateFormat formattedTime = new SimpleDateFormat("dd / MM / yyyy - HH:mm:ss");
        return formattedTime.format(datetime);
    }

    public static Date convertStringDate(String string_date) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = (Date) dateFormat.parse(string_date);
        return date;
    }
    
    public static Date convertStringDateTime(String string_date) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = (Date) dateFormat.parse(string_date);
        return date;
    }
    
    public static ArrayList<String> toList(Enumeration<String> params){
        return Collections.list(params);
    }
    
        // funzioni per la formattazione dell'ora
    public static String formatTime(Date time) {
        SimpleDateFormat formattedTime = new SimpleDateFormat("HH:mm:ss");
        return formattedTime.format(time);
    }
    public static String formatTime(Timestamp time) {
        SimpleDateFormat formattedTime = new SimpleDateFormat("HH:mm:ss");
        return formattedTime.format(time);
    }
    
    /**
     * Crea un path a partire dai nomi delle cartelle (senza che l'utente si preoccupi dei separatori)
     * @param path
     * @return 
     */
    public static String getPath(String ... path) {
        String finalPath = "";
        int bid;
        int eid;
        if(path != null && path.length > 0) {
            for(int i=0;i<path.length;i++)
                if(path[i] != null && !path[i].isEmpty()) {
                    bid = 0;
                    eid = path[i].length();
                    if(path[i].startsWith("/") && i>0)
                        bid = 1;
                    if(path[i].endsWith("/"))
                        eid = eid - 1;
                    if(!finalPath.isEmpty() && finalPath.charAt(finalPath.length() - 1) != '/')
                        finalPath += "/";
                    finalPath += path[i].substring(bid, eid);
                }
        }
        return finalPath;
    }
    
    
    /**
     * Verifica che una stringa data sia composta da caratteri ASCII o meno
     * @param value
     * @return 
     */
    public static boolean isASCII(String value) {
        if(value != null)
            return Charset.forName("US-ASCII").newEncoder().canEncode(value);
        else
            return false;
    }
    
}